package com.damagedboy.base.utils;

import com.damagedboy.base.exception.ReturnInfoException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;

@RestControllerAdvice
public class MyResponseBodyAdvice implements ResponseBodyAdvice {
    private Logger logger = LoggerFactory.getLogger(MyResponseBodyAdvice.class);

    @ExceptionHandler(Exception.class)
    public Object handleAnyException(Exception ex) {
        logger.error(ex.getMessage(), ex);
        return ex;
    }

    @Override
    public Object beforeBodyWrite(Object returnValue, MethodParameter methodParameter,
                                  MediaType mediaType, Class clas, ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse) {
        ApiResult apiResult = new ApiResult();
        if (returnValue instanceof ReturnInfoException) {
            String errorCode = ((ReturnInfoException) returnValue).getErrorCode();
            String message = ((ReturnInfoException) returnValue).getMessage();
            apiResult.setCode(errorCode);
            apiResult.setReturnMessage(message);
            apiResult.setBean(new HashMap<>());
            apiResult.setBeans(new ArrayList<>());
            return apiResult;
        }
        if (returnValue instanceof Exception) {
            apiResult.setCode("500");
            apiResult.setReturnMessage("服务器内部错误");
            apiResult.setBean(new HashMap<>());
            apiResult.setBeans(new ArrayList<>());
            return apiResult;
        }
        apiResult.setCode("0");
        apiResult.setReturnMessage("success");
        if (returnValue instanceof Collection || returnValue instanceof Object[]) {
            apiResult.setBeans(returnValue);
            apiResult.setBean(new HashMap<>());
        } else {
            apiResult.setBean(returnValue);
            apiResult.setBeans(new ArrayList<>());
        }
        return apiResult;
    }

    @Override
    public boolean supports(MethodParameter methodParameter, Class clas) {
        //获取当前处理请求的controller的方法
        String methodName = methodParameter.getMethod().getName();
        // 不拦截/不需要处理返回值 的方法
        String method = "loginCheck"; //如登录
        //不拦截
        return !method.equals(methodName);
    }
}